package hauwei.year2025.month4;

import java.util.HashMap;
import java.util.Scanner;

public class MinSet {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int [][]numbers=new int[n][n];
        HashMap<Integer,int []>numMap=new HashMap<>(); //key是数字，value是下标
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                int number = scanner.nextInt();
                numbers[i][j]= number;
                numMap.put(number,new int[]{i,j});
            }
        }
        for (int []is:numbers){
            for (int i:is){
                System.out.print(i);
            }
            System.out.println();
        }
        int index=1,i=0,j=0;
        int [][]vis=new int[n][n];
        int left=0,right=1,down=0,up=0;
        int count=0;
        while(index<n*n){
            if(numbers[i][j]!=index){
                int []indexs=numMap.get(index+1); //对的下标
                int nextNumber=numbers[indexs[0]][indexs[1]]; //对的下标的数
                int thNumber=numbers[i][j]; //二者进行交换
                numbers[indexs[0]][indexs[1]]=thNumber;
                numbers[i][j]=nextNumber;
                numMap.put(nextNumber,new int[]{i,j});  //重新赋值
                numMap.put(thNumber,new int[]{indexs[0],indexs[1]});
                count++;
            }
            if(right==1){
                if(j+1<n&&vis[i][j+1]==0){
                    j++;
                }else{
                    right=0;
                    down=1;
                    i++;
                }
            } else if(down==1){
                if(i+1<n&&vis[i+1][j]==0){
                    i++;
                }else{
                    down=0;
                    left=1;
                    j--;
                }
            }else if(left==1){
                if(j-1>0&&vis[i][j-1]==0){
                    j--;
                }else{
                    left=0;
                    up=1;
                    i--;
                }
            }else if(up==1){
                if(i-1>0&&vis[i-1][j]==0){
                    i--;
                }else{
                    up=0;
                    left=1;
                    j++;
                }
            }
            index++;
        }
        System.out.println(count);
    }
}
